package pcb.control.commands 
{
	import com.intel.patterns.cairngorm.CairngormEvent;
	import com.intel.utils.Debugger;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	/**
	 * ...
	 * @author Fintan Boyle
	 */
	public class Cmd_loadMenu extends AbstractCommand 
	{
		private var context:LoaderContext;
		
		public function Cmd_loadMenu() 
		{
			context = new LoaderContext();  
			context.applicationDomain = ApplicationDomain.currentDomain;  
		}
		
		override public function execute(event:CairngormEvent):void 
		{
			Debugger.traceOut("Cmd_loadMenu > execute()");
			
			loadMenuRSL();
		}
		
		private function loadMenuRSL():void
		{
			var rsl_loader:Loader = new Loader();
			rsl_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, rsl_loader_onComplete);
			rsl_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loader_onIOError);
			var url:URLRequest = new URLRequest("shared_assets/player/main_menu.swf");
			rsl_loader.load(url, context);		
		}
		
		private function loadMenuXml():void
		{
			var xml_loader:URLLoader = new URLLoader();
			xml_loader.addEventListener(Event.COMPLETE, xml_loader_onComplete);
			xml_loader.addEventListener(IOErrorEvent.IO_ERROR, loader_onIOError);
			xml_loader.load(new URLRequest("menu.xml"));
		}
		
		private function loader_onIOError(e:IOErrorEvent):void 
		{
			Debugger.traceOut("Cmd_loadMenu > loader_onIOError");
			e.target.removeEventListener(Event.COMPLETE, rsl_loader_onComplete);
			e.target.removeEventListener(IOErrorEvent.IO_ERROR, loader_onIOError);
		}
		
		private function rsl_loader_onComplete(e:Event):void 
		{
			Debugger.traceOut("Cmd_loadMenu > rsl_loader_onComplete");
			models.mainMenuModel.setMenuRsl(e.currentTarget.content as MovieClip);
			loadMenuXml();
			
			e.target.removeEventListener(IOErrorEvent.IO_ERROR, loader_onIOError);
			e.target.removeEventListener(Event.COMPLETE, rsl_loader_onComplete);
		}
		
		private function xml_loader_onComplete(e:Event):void 
		{
			Debugger.traceOut("Cmd_loadMenu > xml_loader_onComplete");
			var loader:URLLoader = URLLoader(e.target);
			
			var menuXml:XML = new XML(loader.data)
			var idList:XMLList = menuXml..node.@id;
			
			models.mainMenuModel.setMenuXml(menuXml);
			
			for each (var id:* in idList) {
				models.playerStateModel.addLessonId(id);
			}
			
			models.playerStateModel.setCurrentLessonId(models.lessonStateModel.lessonId);

			e.target.removeEventListener(IOErrorEvent.IO_ERROR, loader_onIOError);
			e.target.removeEventListener(Event.COMPLETE, xml_loader_onComplete);
			
			
		}
		
		
	}
	
}